import { ACCESS_TOKEN_KEY, USER_ID_KEY } from 'constants/index';
import qs from 'qs';
import { atom } from 'recoil';

export interface IUserinfo {
  email: string;
  name: string;
  role: string;
  picture?: string;
}

let defaultAccessToken = localStorage.getItem(ACCESS_TOKEN_KEY) || '';
let defaultUserId = localStorage.getItem(USER_ID_KEY) || '';
if (location.hash.indexOf('access_token') !== -1) {
  try {
    const hash = location.hash;
    const queryString = hash.slice(1);
    const query = qs.parse(queryString);
    const { access_token, userInfo } = query;
    const accessToken = access_token as string;
    const userinfo = userInfo as string;
    const regex = /userId=(\d+)/;
    const matched = userinfo.match(regex);
    if (accessToken && matched) {
      defaultAccessToken = accessToken;
      defaultUserId = matched[1];
      localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
      localStorage.setItem(USER_ID_KEY, matched[1]);
    }
  } catch (e) {
    console.error(e);
  }
}

export const auth0State = atom<{
  isAuthenticated: boolean;
  isLoading: boolean;
  accessToken: string;
  userId: string;
  error: Error | null;
}>({
  key: 'auth0State',
  default: {
    isAuthenticated: !!defaultAccessToken,
    isLoading: false,
    accessToken: defaultAccessToken,
    userId: defaultUserId,
    error: null
  }
});

export const userState = atom<IUserinfo | null>({
  key: 'userState',
  default: null
});
